package org.gdsdxy.pmmp.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.gdsdxy.pmmp.entity.Email;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class EmailDaoImpl extends HibernateDaoSupport implements IEmailDao {

	@Override
	public void deleteEmail(Email email) {
		
	}

	@Override
	public void saveEmail(Email email) {
		this.getHibernateTemplate().saveOrUpdate(email);
	}

	@Override
	public List<Email> selectEmailsByUserId(Integer id) {
		String hql = "from Email e where e.baseInfo.ID = ?";
		return this.getHibernateTemplate().find(hql,new Object[]{id});
	}

  public List<Email> selectEmailsByReceiver(String receiver) {
    String hql = "from Email e where e.receiver = ?";
    return this.getHibernateTemplate().find(hql,new Object[]{receiver});
  }

  public void saveEmails(List<Email> emails) {
    this.getHibernateTemplate().saveOrUpdateAll(emails);
  }

  public Email getById(int id) {
    return (Email) this.getHibernateTemplate().get(Email.class, id);
  }

  public void deleteById(int emailId) {
    Email email = new Email();
    email.setId(emailId);
    this.getHibernateTemplate().delete(email);
  }

  public void deleteByIds(List<Integer> emailIds) {
    List<Email> emails = new ArrayList<Email>();
    for(Integer id : emailIds){
      Email email = new Email();
      email.setId(id);
      emails.add(email);
    }
    this.getHibernateTemplate().deleteAll(emails);
  }

  public void update(Email email) {
    this.getHibernateTemplate().saveOrUpdate(email);
  }

  public List<Email> selectEmailsByReceiverByFy(final String receiver, final int start,final int size) {
    final String hql = "from Email where receiver = ? order by id";
    List emails =  (List)this.getHibernateTemplate().execute(new HibernateCallback(){
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery(hql);
        query.setString(0, receiver);
        query.setFirstResult(start);
        query.setMaxResults(size);
        return query.list();
      }
      
    });
    return emails;
  }

  public long countEmails(String receiver) {
    String hql = "select count(*) from Email where receiver = ? ";
    List list = this.getHibernateTemplate().find(hql,new Object[]{receiver});
    long count = (list!=null&&list.size()>0)?(Long)list.get(0): 0L;
    return count;
  }

}
